package tcpnetwork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpClient {
    private Socket socket;

    public TcpClient(String serverIP, int serverPort) throws IOException {
        socket = new Socket(serverIP, serverPort);//连接服务器
    }

    public void start() {
        //用户从控制台输入请求
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            //给 OutputStream 套壳
            PrintWriter writer = new PrintWriter(outputStream);
            //给 InputStream 套壳
            Scanner scanner2 = new Scanner(inputStream);
            while(true) {
                //可能会有多次请求
                String request = scanner.next();
                //发送请求
                writer.println(request);
                writer.flush();
                //接收响应
                String response = scanner2.next();
                //打印响应
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpClient client = new TcpClient("127.0.0.1",9090);
        client.start();
    }
}
